package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.GoodsConstant;
import com.zb.entity.*;
import com.zb.mapper.ZjSpareMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.utils.RandomUtil;
import com.zb.utils.VerificUtil;
import com.zb.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 备件表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-15
 */
@Service
public class ZjSpareServiceImpl extends ServiceImpl<ZjSpareMapper, ZjSpare> implements ZjSpareService {
    @Resource
    private ZjSpareMapper spareMapper;
    @Resource
    private ZjBrandService brandService;
    @Resource
    private ZjSpareImageService imageService;
    @Resource
    private ZjSpareSpecInfoService specInfoService;
    @Resource
    private ZjSpareIntroduceService introduceService;
    @Resource
    private ZjSpareRelationParamService paramService;
    @Resource
    private ZjSpareCustomParamService customParamService;
    @Resource
    private ZjFactorySpareService factorySpareService;

    // 新增或修改备件
    @Override
    @Transactional
    public void save(AccounLoginInfo loginInfo, GoodsVo goodsVo) {
        Assert.isTrue(null != goodsVo.getModel() && goodsVo.getModel().length() <= 300, "商品型号限制300个字符以内！", goodsVo.getModel());
        Assert.isTrue(null != goodsVo.getName() && goodsVo.getName().length() <= 300, "商品名称限制300个字符以内！", goodsVo.getName());
        Assert.isTrue(null == spareMapper.existByModel(loginInfo.getCustAccId(), goodsVo.getId(), goodsVo.getModel()), "商品型号已重复！", goodsVo.getModel());
        if (null != goodsVo.getBrandId()) {
            ZjBrand brand = brandService.getById(goodsVo.getBrandId());
            Assert.isTrue(null != brand, "品牌ID参数[" + goodsVo.getBrandId() + "]的数据不存在！");
            goodsVo.setBrand(brand.getName());
        }
        if (StringUtils.isNotBlank(goodsVo.getCode())) {
            Assert.isTrue(null == spareMapper.existByCode(loginInfo.getCustAccId(), goodsVo.getId(), goodsVo.getCode()), "商品编码已重复！", goodsVo.getCode());
        }
        if (StringUtils.isNotBlank(goodsVo.getItemNumber())) {
            Assert.isTrue(null == spareMapper.existByItemNumber(loginInfo.getCustAccId(), goodsVo.getId(), goodsVo.getItemNumber()), "商品货号已重复！", goodsVo.getItemNumber());
        }
        if (StringUtils.isNotBlank(goodsVo.getSupplierTelephone())) {
            Assert.isTrue(VerificUtil.phoneVerific(goodsVo.getSupplierTelephone()) || VerificUtil.telephoneVerific(goodsVo.getSupplierTelephone()), "供应商联系电话格式不正确，请填写座机或手机号的正确格式");
        }
        ZjSpare spare = new ZjSpare();
        BeanUtils.copyProperties(goodsVo, spare);
        spare.setDisabled(goodsVo.getStatus());
        spare.setTypeId(null == spare.getTypeId()? 0L : spare.getTypeId());
        spare.setType(null == spare.getType()? "" : spare.getType());
        if (null != spare.getId()) {
            this.updateById(spare);
        } else {
            spare.setId(IdWorker.getId());
            spare.setCustAccId(loginInfo.getCustAccId());
            spare.setBrandId(null == spare.getBrandId()? 0L : spare.getBrandId());
            spare.setBrand(null == spare.getBrand()? "" : spare.getBrand());
            spare.setName(StringUtils.isNotBlank(spare.getName())? spare.getName() : spare.getModel());
            spare.setCode(StringUtils.isNotBlank(spare.getCode())? spare.getCode() : "BM" + RandomUtil.random10());
            spare.setItemNumber(StringUtils.isNotBlank(spare.getItemNumber())? spare.getItemNumber() : "HH" + RandomUtil.random10());
            spare.setSource(GoodsConstant.SOURCE_1);
            spare.setSupplier(null == spare.getSupplier()? "" : spare.getSupplier());
            spare.setSupplierTelephone(null == spare.getSupplierTelephone()? "" : spare.getSupplierTelephone());
            spare.setDeleted(false);
            spare.setCreateEmpId(loginInfo.getId());
            spare.setUpdateEmpId(loginInfo.getId());
            this.save(spare);
        }
        specInfoService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getSpecVos(), goodsVo.getDelSepcIds());
        imageService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getImageVos(), goodsVo.getDelImageIds());
        introduceService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getContent());
        paramService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getParamValVo());
        customParamService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getCustomParamVos(), goodsVo.getDelCustomParamIds());
        factorySpareService.save(loginInfo.getCustAccId(), spare.getId(), goodsVo.getFactoryIds());
    }

    // 获取备件列表
    @Override
    public Map<String, Object> getList(Long custAccId, GoodsSelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        long count = spareMapper.pageListCount(custAccId, selectVo);
        if (count <= 0) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, new ArrayList<>());
        }
        List<GoodsListVo> voList = spareMapper.pageList(custAccId, selectVo);
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, voList);
    }

    // 批量启用或禁用备件
    @Override
    public void updateBatchDisabledByIds(List<Long> idList, boolean status) {
        spareMapper.updateBatchDisabledByIds(idList, status);
    }

    // 根据品牌ID更新品牌名称
    @Override
    public void updateBrandByBrandId(Long brandId, String brand) {
        spareMapper.updateBrandByBrandId(brandId, brand);
    }

    // 根据分类ID更新商品分类名称
    @Override
    public void updateTypeByTypeId(Long typeId, String type) {
        spareMapper.updateTypeByTypeId(typeId, type);
    }

    // 根据单位ID更新商品单位名称
    @Override
    public void updateUnitByUnitId(Long unitId, String unit) {
        spareMapper.updateUnitByUnitId(unitId, unit);
    }

    // 分页获取备件下拉数据列表
    @Override
    public Map<String, Object> pageSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        List<ZjSpare> spares = spareMapper.pageSelect(custAccId, selectVo);
        List<SelectGoodsVo> voList = spares.stream().map(spare -> {
            SelectGoodsVo vo = new SelectGoodsVo(spare.getId(), spare.getName(), "");
            vo.setModel(spare.getModel());
            vo.setItemNumber(spare.getItemNumber());
            vo.setCode(spare.getCode());
            vo.setBrandId(spare.getBrandId());
            vo.setBrand(spare.getBrand());
            vo.setTypeId(spare.getTypeId());
            vo.setType(spare.getType());
            return vo;
        }).toList();
        List<Long> spareIds = voList.stream().map(SelectResultVo::getId).toList();
        // 获取备件图片
        List<ZjSpareImage> infos = imageService.getImageBySpareIds(spareIds);
        voList.forEach(t -> {
            t.setImage(infos.stream().filter(info -> Objects.equals(t.getId(), info.getSpareId())).map(ZjSpareImage::getImage).findFirst().orElse(""));
        });
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), spareMapper.pageSelectCount(custAccId, selectVo), voList);
    }

    // 根据备件ID获取备件详情GoodesDetailVo
    @Override
    public GoodesDetailVo getDetail(Long id) {
        ZjSpare spare = this.getById(id);
        Assert.isTrue(null != spare, "备件参数[" + id + "]的数据不存在");
        List<ZjSpareImage> imageList = imageService.getBySpareId(id);
        return GoodesDetailVo.beanToVo(spare, imageList.stream().map(ZjSpareImage::getImage).toList());
    }

    // 根据备件ID获取产品修改前的信息
    @Override
    public GoodsVo getInfo(Long id) {
        ZjSpare spare = this.getById(id);
        Assert.isTrue(null != spare, "备件参数[" + id + "]的数据不存在");

        GoodsVo vo = new GoodsVo();
        BeanUtils.copyProperties(spare, vo);
        vo.setStatus(spare.getDisabled());
        vo.setContent(introduceService.getByProductId(id));
        vo.setSpecVos(specInfoService.getBySpareId(id).stream().map(spec -> {
            GoodsSpecInfoVo infoVo = new GoodsSpecInfoVo();
            BeanUtils.copyProperties(spec, infoVo);
            return infoVo;
        }).toList());
        vo.setImageVos(imageService.getBySpareId(id).stream().map(img -> {
            return  new GoodsImageVo(img.getId(), img.getImage());
        }).toList());
        vo.setParamValVo(paramService.getParamBySpareId(id));
        vo.setCustomParamVos(customParamService.getBySpareId(id).stream().map(cu -> {
            return new GoodsCustomParamVo(cu.getId(), cu.getName(), cu.getVal());
        }).toList());
        vo.setFactoryIds(factorySpareService.getBySpareId(id).stream().map(ZjFactorySpare::getFactoryId).toList());
        return vo;
    }

    // 根据备件ID获取产品参数
    @Override
    public GoodsDetailParamVo getSpareParam(Long id) {
        GoodsDetailParamVo paramVo = paramService.getBySpareId(id);
        List<ZjSpareCustomParam> spareCustomParams = customParamService.getBySpareId(id);

        List<GoodsCustomParamVo> customParamVos = spareCustomParams.stream().map(vo -> {
            GoodsCustomParamVo customParam = new GoodsCustomParamVo();
            customParam.setId(vo.getId());
            customParam.setName(vo.getName());
            customParam.setVal(vo.getVal());
            return customParam;
        }).toList();
        if (null == paramVo) {
            paramVo = new GoodsDetailParamVo();
        }
        paramVo.setCustomParams(customParamVos);
        return paramVo;
    }

    // 根据备件ID获取备件信息
    @Override
    public List<GoodsInfo> getInfoByIds(List<Long> idList) {
        QueryWrapper<ZjSpare> wrapper = new QueryWrapper<>();
        wrapper.select("id", "gmt_create");
        wrapper.in("id", idList);
        return this.list(wrapper).stream().map(vo -> {
            GoodsInfo info = new GoodsInfo();
            info.setId(vo.getId());
            info.setDate(vo.getGmtCreate());
            return info;
        }).toList();
    }

    // 分页获取备件ID集合
    @Override
    public List<Long> pageGetIds(GoodsSelect goodsSelect) {
        return spareMapper.pageGetIds(goodsSelect);
    }

    // 根据备件ID删除
    @Override
    @Transactional
    public void deleteBatchById(List<Long> ids) {
        specInfoService.deleteBatchBySpareIds(ids);
        imageService.deleteBatchBySpareIds(ids);
        introduceService.removeByIds(ids);
        paramService.deleteBatchBySpareIds(ids);
        customParamService.deleteBatchBySpareIds(ids);
        factorySpareService.deleteBySpareIds(ids);
        this.removeByIds(ids);
    }

    // 根据品牌ID查询关联配件的品牌
    @Override
    public List<String> getRelationBranByBrandIds(List<Long> brandIds) {
        if (null == brandIds || brandIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjSpare> wrapper = new QueryWrapper<>();
        wrapper.select("name");
        wrapper.in("brand_id", brandIds);
        return this.list(wrapper).stream().map(ZjSpare::getBrand).toList();
    }

    // 根据商品类型ID获取关联的备件分类
    @Override
    public List<ZjSpare> getRelationTypeByTypeIds(List<Long> typeIds) {
        return spareMapper.getRelationTypeByTypeIds(typeIds);
    }

    // 根据商品单位ID获取关联的备件单位
    @Override
    public List<ZjSpare> getRelationUnitByUnitIds(List<Long> unitIds) {
        return spareMapper.getRelationUnitByUnitIds(unitIds);
    }
}
